package com.zc.runner.admin.controller;

import com.zc.runner.admin.form.ModifyPwdForm;
import com.zc.runner.core.domain.Manager;
import com.zc.runner.core.repository.ManagerRepository;
import com.zc.runner.core.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/manager")
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private ManagerRepository managerRepository;

    @GetMapping("/profile")
    public String profile(HttpSession session, Model model){

        Manager manager = (Manager) session.getAttribute("manager");
        Manager manager1 = managerService.get(manager.getId());
        model.addAttribute("manager",manager);
        return "manager/profile";
    }

    @GetMapping("/modifyPwd")
    public String modifyPwd(){
        return "manager/modifyPwd";
    }


    @PostMapping("/modifyPwd")
    public String modifyPwd(@Validated ModifyPwdForm modifyPwdForm,
                            BindingResult bindingResult,
                            HttpSession session,
                            Model model){
        if (bindingResult.hasErrors()){
            model.addAttribute("errorMsg",getErrorMessage(bindingResult));
            return "manager/modifyPwd";
        }
        Manager manager = (Manager) session.getAttribute("manager");
        manager.setPassword(modifyPwdForm.getPassword());
        Manager result = managerService.modifyPwd(manager.getId(),manager.getPassword());
        if (result != null) {
       //修改密码成功
            session.setAttribute("manager",result);
            model.addAttribute("manager",result);
            return "manager/profile";
    } else {
        //修改失败
        return null;
    }
    }


    private String getErrorMessage(BindingResult bindingResult){
        StringBuilder errorMsg = new StringBuilder();
        int i = 0;
        for (ObjectError error : bindingResult.getAllErrors()) {
            if (i != 0) {
                errorMsg.append("<br/>");
            }
            errorMsg.append(error.getDefaultMessage());
            i++;
        }
        return errorMsg.toString();
    }
}
